package com.lzh.excel.imports.strategy;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.write.merge.AbstractMergeStrategy;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

import java.util.Iterator;
import java.util.List;

/**
 * @author zhehen.lu
 * @date 2025/8/3 14:35
 */
public class CustomMergeCellStrategy extends AbstractMergeStrategy {
    private Integer rowIndex;
    private Integer targetColumnIndex;
    private List<Integer> exportFieldGroupCountList;

    public CustomMergeCellStrategy(Integer targetColumnIndex, List<Integer> exportFieldGroupCountList) {
        this.targetColumnIndex = targetColumnIndex;
        this.exportFieldGroupCountList = exportFieldGroupCountList;
    }

    @Override
    protected void merge(Sheet sheet, Cell cell, Head head, Integer integer) {
        if (null == this.rowIndex) {
            this.rowIndex = cell.getRowIndex();
        }

        if (cell.getRowIndex() == this.rowIndex && cell.getColumnIndex() == this.targetColumnIndex) {
            this.mergeGroupColumn(sheet);
        }

    }

    private void mergeGroupColumn(Sheet sheet) {
        int rowCount = this.rowIndex;
        Iterator iterator = this.exportFieldGroupCountList.iterator();

        while(iterator.hasNext()) {
            Integer count = (Integer)iterator.next();
            if (count == 1) {
                rowCount += count;
            } else {
                CellRangeAddress cellRangeAddress = new CellRangeAddress(rowCount, rowCount + count - 1, this.targetColumnIndex, this.targetColumnIndex);
                sheet.addMergedRegionUnsafe(cellRangeAddress);
                rowCount += count;
            }
        }

    }
}
